package ogl.vecmathimp;

import java.nio.FloatBuffer;

import org.lwjgl.BufferUtils;

import ogl.vecmath.Color;
import ogl.vecmath.Vector;

public class ColorImp implements Color {

	private float [] c = new float[3];
	
	public float getR() {
		return c[0];
	};

	public float getG() {
		return c[1];
	};

	public float getB() {
		return c[2];
	};

	public ColorImp(float r, float g, float b) {
		this.c[0] = r;
		this.c[1] = g;
		this.c[2] = b;
	}

	public ColorImp(Vector v) {
		this.c[0] = v.x();
		this.c[1] = v.y();
		this.c[2] = v.z();
	}

	@Override
	public boolean isBlack() {
		return (c[0] == 0.0 && c[1] == 0.0 && c[2] == 0.0);
	}

	@Override
	public Color add(ColorImp a) {
		return new ColorImp(c[0] + a.getR(), c[1] + a.getG(), c[2] + a.getB());
	}

	@Override
	public Color modulate(float s) {
		return new ColorImp(c[0] * s, c[1] * s, c[2] * s);
	}

	@Override
	public Color modulate(ColorImp m) {
		return new ColorImp(c[0] * m.getR(), c[1] * m.getG(), c[2] * m.getB());
	}

	@Override
	public Color clip() {
		ColorImp c = new ColorImp(Math.min(getR(), 1), Math.min(getG(), 1), Math.min(
				getB(), 1));
		return new ColorImp(Math.max(c.getR(), 0), Math.max(c.getG(), 0),
				Math.max(c.getB(), 0));
	}

	@Override
	public float[] asArray() {
		return new float[] { c[0], c[1], c[2] };
	}

	@Override
	public FloatBuffer asBuffer() {
		FloatBuffer buf = BufferUtils.createFloatBuffer(size());
		buf.put(c[0]);
		buf.put(c[1]);
		buf.put(c[2]);
		buf.rewind();
		return buf;
	}

	@Override
	public void fillBuffer(FloatBuffer buf) {
		buf.put(c[0]);
		buf.put(c[1]);
		buf.put(c[2]);
	}

	@Override
	public int toAwtColor() {
		ColorImp c = (ColorImp) clip();
		return (toInt(1.0f) << 24) | (toInt(c.getR()) << 16)
				| (toInt(c.getG()) << 8) | toInt(c.getB());
	}

	private static int toInt(float f) {
		return Math.round(f * 255.0f);
	}

	@Override
	public int compareTo(Color o) {
		if (c[0] != o.getR()) {
			return ((c[0] < o.getR()) ? 1 : -1);
		}
		if (c[1] != o.getG()) {
			return ((c[1] < o.getG()) ? 1 : -1);
		}
		if (c[2] != o.getB()) {
			return ((c[2] < o.getB()) ? 1 : -1);
		}
		return 0;
	}

	@Override
	public int size() {
		return getSize();
	}
	
	public static int getSize(){
		return 3;
	}

}
